<?php

/**
 * Menashop
 *
 * LICENSE
 *
 * This source file is subject to the license that is bundled
 * with this project in the file LICENSE.txt
 *
 * @category   Menashop
 * @package    Menashop_Content
 * @subpackage Categories
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

/**
 * The SAX handler for categories
 * 
 * @category   Menashop
 * @package    Menashop_Content
 * @subpackage Categories
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 */
class Menashop_Content_Categories
{

    /**
     * The data model for category
     * @var Admin_Model_Category
     */
    protected $_categoryModel;

    /**
     * The data model for category translation
     * @var Admin_Model_CategoryTranslation
     */
    protected $_categoryTranslationModel;

    /**
     * IDs of languages
     * @var array
     */
    protected $_languages;

    /**
     * Category
     * @var Admin_Model_Category
     */
    protected $_category;

    /**
     * Category translation
     * @var array
     */
    protected $_categoryTranslations;

    /**
     * The counter for categories
     * @var integer 
     */
    protected $_totalCategories = 0;

    /**
     * The counter for inserted categories
     * @var ineteger 
     */
    protected $_totalCategoriesInserted = 0;

    /**
     * The counter for updated categories
     * @var integer 
     */
    protected $_totalCategoriesUpdated = 0;

    /**
     * The counter for category translations
     * @var integer 
     */
    protected $_totalCategoryTranslations = 0;

    /**
     * The counter for inserted category translations
     * @var ineteger 
     */
    protected $_totalCategoryTranslationsInserted = 0;

    /**
     * The counter for updated category translations
     * @var integer 
     */
    protected $_totalCategoryTranslationsUpdated = 0;

    /**
     * The config
     * @var Menashop_Downloader
     */
    protected $_config;

    /**
     * The downloader for files
     * @var Menashop_Downloader
     */
    protected $_downloader;

    /**
     * Local images path
     * @var string
     */
    protected $_localImagesPath = null;

    /**
     * Local images URL
     * @var string
     */
    protected $_localImagesUrl = null;

    /**
     * Base content URL
     * @var string
     */
    protected $_baseContentUrl = null;

    /**
     * Initialize the SAX handler for categories
     * @param array $languages 
     * @param Zend_config $config $config
     * @param Menashop_Downloader $downloader
     */
    public function __construct($languages, $config, $downloader)
    {
        $this->_categoryModel = new Admin_Model_Category();
        $this->_categoryTranslationModel = new Admin_Model_CategoryTranslation();
        $this->_languages = $languages;
        $this->_config = $config;
        $this->_downloader = $downloader;
        $this->_localImagesPath = $this->_config->localImagesPath;
        $this->_localImagesUrl = $this->_config->localImagesUrl;
        $this->_baseContentUrl = $this->_config->baseUrl;
    }

    /**
     * Save images for category
     */
    protected function _saveCategoryImages()
    {

        // Save category thumb pic
        $thumbUrl = $this->_category['thumb_pic'];
        if ($thumbUrl) {
            $localPath = $this->_localImagesPath . substr($thumbUrl, strpos($thumbUrl, $this->_baseContentUrl) + strlen($this->_baseContentUrl));
            $localUrl = $this->_localImagesUrl . substr($thumbUrl, strpos($thumbUrl, $this->_baseContentUrl) + strlen($this->_baseContentUrl));

            // Check directory for local path
            $parentPath = dirname($localPath);
            if (!file_exists($parentPath)) {
                mkdir($parentPath, 0775, true);
            }

            if (!file_exists($localPath)) {
                $this->_downloader->downloadFile($thumbUrl, $localPath);
            }
            $this->_category['thumb_pic'] = $localUrl;
        }

        // Save category low pic
        $lowUrl = $this->_category['low_pic'];
        if ($lowUrl) {
            $localPath = $this->_localImagesPath . substr($lowUrl, strpos($lowUrl, $this->_baseContentUrl) + strlen($this->_baseContentUrl));
            $localUrl = $this->_localImagesUrl . substr($lowUrl, strpos($lowUrl, $this->_baseContentUrl) + strlen($this->_baseContentUrl));

            // Check directory for local path
            $parentPath = dirname($localPath);
            if (!file_exists($parentPath)) {
                mkdir($parentPath, 0775, true);
            }
            if (!file_exists($localPath)) {
                $this->_downloader->downloadFile($lowUrl, $localPath);
            }
            $this->_category['low_pic'] = $localUrl;
        }
    }

    /**
     * Process the start of an element in XML
     * @param obejct $parser
     * @param string $tag
     * @param array $attributes 
     */
    public function startElement($parser, $tag, $attributes)
    {
        if ('Category' == $tag) {
            $this->_category = array();
            $this->_category['content_id'] = $attributes['ID'];
            $this->_category['low_pic'] = $attributes['LowPic'];
            $this->_category['thumb_pic'] = $attributes['ThumbPic'];
            $this->_category['uncat_id'] = $attributes['UNCATID'];
            $this->_categoryTranslations = array();
        } elseif ('Name' == $tag) {
            // check a category translation for the current language 
            if (isset($attributes['Value']) && in_array($attributes['langid'], $this->_languages)) {
                $categoryTranslation = null;
                // check a category translation
                if (isset($this->_categoryTranslations[$attributes['langid']])) {
                    $categoryTranslation = &$this->_categoryTranslations[$attributes['langid']];
                } else {
                    // create a new category translation
                    $categoryTranslation = array();
                    $categoryTranslation['language_id'] = $attributes['langid'];
                    $this->_categoryTranslations[$attributes['langid']] = &$categoryTranslation;
                    $this->_totalCategoryTranslations++;
                }
                $categoryTranslation['name'] = $attributes['Value'];
            }
        } elseif ('Description' == $tag) {
            // check a category translation for the current language
            if (in_array($attributes['langid'], $this->_languages)) {
                $categoryTranslation = null;
                // check a category translation
                if (isset($this->_categoryTranslations[$attributes['langid']])) {
                    $categoryTranslation = &$this->_categoryTranslations[$attributes['langid']];
                } else {
                    // create a new category translation
                    $categoryTranslation = array();
                    $categoryTranslation['language_id'] = $attributes['langid'];
                    $this->_categoryTranslations[$attributes['langid']] = &$categoryTranslation;
                    $this->_totalCategoryTranslations++;
                }
                $categoryTranslation['description'] = $attributes['Value'];
            }
        }
    }

    /**
     * Process the end of an element in XML
     * @param object $parser
     * @param string $tag 
     */
    public function endElement($parser, $tag)
    {
        if ('Category' == $tag) {
            // find a category in the database
            $categoryId = $this->_categoryModel->findIdByContentId($this->_category['content_id']);
            if ($categoryId) {
                // update the category
                $this->_category['id'] = $categoryId;
                $this->_totalCategoriesUpdated++;
            } else {
                // insert the category
                $this->_totalCategoriesInserted++;
            }
            $this->_saveCategoryImages();
            $categoryId = $this->_categoryModel->save($this->_category);
            foreach ($this->_categoryTranslations as $languageId => $categoryTranslation) {
                $categoryTranslationId = $this->_categoryTranslationModel->findIdByCategoryAndLanguage($categoryId, $languageId);
                if ($categoryTranslationId) {
                    // update the category translation
                    $categoryTranslation['id'] = $categoryTranslationId;
                    $this->_totalCategoryTranslationsUpdated++;
                } else {
                    // insert the category translation
                    $this->_totalCategoryTranslationsInserted++;
                }
                $categoryTranslation['category_id'] = $categoryId;
                $this->_categoryTranslationModel->save($categoryTranslation);
            }
            $this->_totalCategories++;
        }
    }

    /**
     * Process characters in XML
     * @param object $parser
     * @param string $data 
     */
    public function characterData($parser, $data)
    {
        
    }

    /**
     * The report about a parsing
     * @return string 
     */
    public function getReport()
    {
        $report = "$this->_totalCategories categories in XML,";
        $report .= " $this->_totalCategoriesInserted inserted,";
        $report .= " $this->_totalCategoriesUpdated updated\n";
        $report .= "$this->_totalCategoryTranslations category translations in XML,";
        $report .= " $this->_totalCategoryTranslationsInserted inserted,";
        $report .= " $this->_totalCategoryTranslationsUpdated updated";
        return $report;
    }

}

